package tokenhelper

import (
	"errors"
	"strings"
	"time"

	"gitee.com/fkil555/gin-extend/conf"
	"github.com/golang-jwt/jwt/v4"
)

type GenerateJwtStruct struct {
	Uid        int64
	ExtendInfo string
	jwt.RegisteredClaims
}

func (g *GenerateJwtStruct) GenerateJwtToken() (token string, err error) {
	if len(conf.GEConf.AppConfig.TokenAccessSecret) <= 0 || conf.GEConf.AppConfig.TokenAccessExpire <= 0 {
		err = errors.New("token access secret or token access expire invalid")
		return
	}

	tokenVal := GenerateJwtStruct{
		Uid:        g.Uid,
		ExtendInfo: g.ExtendInfo,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(
				time.Now().Add(
					time.Duration(conf.GEConf.AppConfig.TokenAccessExpire) * time.Second),
			),
		},
	}

	claims := jwt.NewWithClaims(jwt.SigningMethodHS256,
		tokenVal,
	)

	token, err = claims.SignedString([]byte(conf.GEConf.AppConfig.TokenAccessSecret))
	token = "Bearer " + token
	return
}

func ParseJwtToken(tokenStr string) (*GenerateJwtStruct, error) {
	if len(tokenStr) > 7 && strings.ToUpper(tokenStr[0:7]) == "BEARER " {
		tokenStr = tokenStr[7:]
	}
	jwtStruct := GenerateJwtStruct{}
	_, err := jwt.ParseWithClaims(
		tokenStr,
		&jwtStruct,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(conf.GEConf.AppConfig.TokenAccessSecret), nil
		},
	)

	if err == nil {
		return &jwtStruct, nil
	} else {
		return nil, err
	}
}
